package com.chinaoryx.dwr;

import java.io.FileReader;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.io.IOUtils;
import org.apache.derby.drda.NetworkServerControl;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class InitServlet extends HttpServlet {

	@Override
	public void init(ServletConfig config) throws ServletException {
		
		super.init(config);
		try {
//			Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
			
//			Properties props = new Properties();
//			props.put("user", "test"); 
//			props.put("password", "test");
			//create and connect the database named helloDB
//			conn=DriverManager.getConnection("jdbc:derby:helloDB;create=true", props);
			
			NetworkServerControl derbyServer = new NetworkServerControl(InetAddress.getByName("localhost"),
					1899,
					"test",
					"test");
			
			 PrintWriter pw = new PrintWriter(System.out);
			 derbyServer.start(pw);
			
			
			System.out.println("create and connect to helloDB");
			
			
			
			
			String resource = "Configuration.xml";
			Reader reader = Resources.getResourceAsReader(resource);
			SqlSessionFactory sqlMapper = new SqlSessionFactoryBuilder().build(reader);
			SqlSession sqlSession = sqlMapper.openSession();
			Connection conn = sqlSession.getConnection();
			conn.setAutoCommit(true);
			
			ScriptRunner runner = new ScriptRunner(conn);
		    runner.runScript(Resources.getResourceAsReader("test.sql"));
			
			
//			ClassLoader cl = this.getClass().getClassLoader();
//			InputStream in = cl.getResourceAsStream("test.sql");
//			String query = IOUtils.toString(in);
//			in.close();
//			
//			
//			PreparedStatement stmt = conn.prepareStatement(query);
//			stmt.execute();
//			stmt.close();

			conn.close();
//			IOUtils.tos
			
		} catch (Exception e) {
			
			e.printStackTrace();
		} 
	}

}
